package org.everyday;

import java.util.*;

/**
 * @version v1.0.0
 * 创建时间：2022/7/13 09:11
 */
public class L735 {
    public int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> stack = new Stack<>();
        for(int i =0;i<asteroids.length;i++){
            boolean alive = true;
            int aster = asteroids[i];
            while (alive && aster < 0 && !stack.isEmpty() && stack.peek() > 0) {
                alive = stack.peek() < -aster; // aster 是否存在
                if (stack.peek() <= -aster) {  // 栈顶行星爆炸
                    stack.pop();
                }
            }
            if (alive) {
                stack.push(aster);
            }
        }
        return stack.stream().mapToInt(x -> x).toArray();
    }

    private int[] test(int[] asteroids){
        Deque<Integer> stack = new ArrayDeque<Integer>();
        for (int aster : asteroids) {
            boolean alive = true;
            while (alive && aster < 0 && !stack.isEmpty() && stack.peek() > 0) {
                alive = stack.peek() < -aster; // aster 是否存在
                if (stack.peek() <= -aster) {  // 栈顶行星爆炸
                    stack.pop();
                }
            }
            if (alive) {
                stack.push(aster);
            }
        }
        int size = stack.size();
        int[] ans = new int[size];
        for (int i = size - 1; i >= 0; i--) {
            ans[i] = stack.pop();
        }
        return ans;
    }

    public static void main(String[] args) {
//        new L735().asteroidCollision(new int[]{-2,-1,1,2});
        new L735().test(new int[]{-2,-1,1,2});
    }
}
